﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;

namespace NKD07.Admin
{
    public partial class edit_product : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                LoadCategory();
                LoadProductInfo();
            }
        }

        // load and show all name of categories in database
        private void LoadCategory()
        {
            Classes.category category = new Classes.category();
            DataTable tb = category.getAllCategories();
            dlCaregories.DataSource = tb;
            dlCaregories.DataBind();
        }

        // load all information of product to edit
        private void LoadProductInfo()
        {
            string strProductID = Request.QueryString["productID"];
            int intProductID = -1;
            try
            {
                intProductID = int.Parse(strProductID);
            }
            catch (Exception)
            {
                intProductID = -1;
            }
            if (intProductID != -1)
            {
                Classes.product product = new Classes.product();
                DataTable tb = product.GetProductByID(intProductID);
                dlProductInfo.DataSource = tb;
                dlProductInfo.DataBind();
                string categoryID = tb.Rows[0]["idCategory"].ToString();
                string manufacturerID = tb.Rows[0]["idManufacturer"].ToString();
                LoadCategoryList(categoryID);
                LoadManufacturerList(manufacturerID);

                // initialize value for calendar control
                //AjaxControlToolkit.CalendarExtender calendar = (AjaxControlToolkit.CalendarExtender)dlProductInfo.FindControl("cldDateAdded");
               // calendar.SelectedDate = DateTime.Today;
            }
        }

        // load all categories to edit infor of product
        private void LoadCategoryList(string categoryID)
        {
            int selectIndex = 0;
            Classes.category category = new Classes.category();
            DataTable tb = category.getAllCategories();
            DropDownList ddlCategory = (DropDownList)dlProductInfo.FindControl("ddlCategory");
            for(int index=0;index<tb.Rows.Count;index++)
            {
                if (categoryID.Equals(tb.Rows[index]["id"].ToString()))
                    selectIndex = index;
                ddlCategory.Items.Add(new ListItem(tb.Rows[index]["name"].ToString(),tb.Rows[index]["id"].ToString()));
            }
            ddlCategory.SelectedIndex = selectIndex;

        }

        // load all manufacturer to edit infor of product
        private void LoadManufacturerList(string manufacturerID)
        {
            int selectIndex = 0;
            Classes.manufacturer manufacturer = new Classes.manufacturer();
            DataTable tb = manufacturer.getAllManufacturer();
            DropDownList ddlCategory = (DropDownList)dlProductInfo.FindControl("ddlPublisher");
            for (int index = 0; index < tb.Rows.Count; index++)
            {
                if (manufacturerID.Equals(tb.Rows[index]["id"].ToString()))
                    selectIndex = index;
                ddlCategory.Items.Add(new ListItem(tb.Rows[index]["name"].ToString(), tb.Rows[index]["id"].ToString()));
            }
            ddlCategory.SelectedIndex = selectIndex;
        }

        // update informations of product and save them into database
        protected void btnUpdate_Click(object sender, EventArgs e)
        {
            int productID = int.Parse(Request.QueryString["productID"]);
            TextBox txtName = (TextBox)dlProductInfo.FindControl("txtName");
            string productName = txtName.Text.Trim();

            TextBox txtDescription = (TextBox)dlProductInfo.FindControl("txtDescription");
            string productDescription = txtDescription.Text.Trim();

            TextBox txtStock = (TextBox)dlProductInfo.FindControl("txtStock");
            string productStock = txtStock.Text.Trim();

            TextBox txtNumberLike = (TextBox)dlProductInfo.FindControl("txtNumberLike");
            string productNumberLike = txtNumberLike.Text.Trim();

            TextBox txtNumberDislike = (TextBox)dlProductInfo.FindControl("txtNumberDislike");
            string productNumberDislike = txtNumberDislike.Text.Trim();

            TextBox txtPriceSell = (TextBox)dlProductInfo.FindControl("txtPriceSell");
            string productPriceSell = txtPriceSell.Text.Trim();

            TextBox txtMapping = (TextBox)dlProductInfo.FindControl("txtMapping");
            string productMapping = txtMapping.Text.Trim();

            DropDownList ddlCategory = (DropDownList)dlProductInfo.FindControl("ddlCategory");
            string productCategory = ddlCategory.SelectedValue;

            DropDownList ddlPublisher = (DropDownList)dlProductInfo.FindControl("ddlPublisher");
            string productPublisher = ddlPublisher.SelectedValue;

            AjaxControlToolkit.CalendarExtender cldDateAdded = (AjaxControlToolkit.CalendarExtender)dlProductInfo.FindControl("cldDateAdded");
            DateTime productDateAdded = cldDateAdded.SelectedDate.Value;

            string productImage = "";
            FileUpload fileUpload = (FileUpload)dlProductInfo.FindControl("fuProductImage");
            if (fileUpload.HasFile)
            {
                try
                {
                    fileUpload.SaveAs(Server.MapPath("~/images/Products/") + fileUpload.FileName);
                    productImage = "./images/Products/" + fileUpload.FileName;
                }
                catch(Exception)
                {
                    Page.ClientScript.RegisterStartupScript(this.GetType(), "alertUpdate", "UploadResult('There is problem uploading your image! upload failed...');",true);
                    return;
                }
            }

            Classes.product product = new Classes.product();
            product.Id = productID;
            product.Name = productName;
            product.Description = productDescription;
            product.NumberLike = int.Parse(productNumberLike);
            product.NumberDislike = int.Parse(productNumberDislike);
            product.PriceSell = float.Parse(productPriceSell);
            product.IdCategory = int.Parse(productCategory);
            product.IdManufacturer = int.Parse(productPublisher);
            product.Mapping = productMapping;
            product.Stock = int.Parse(productStock);
            product.ImageUrl = productImage;
            product.DateAdded = productDateAdded;

            bool result =  product.UpdateProductInfo(product);
            if (result == false)
            {
                Page.ClientScript.RegisterStartupScript(this.GetType(), "alertUpdate", "UploadResult('Update failed! Please try again... ');", true);
                return;
            }
            else
            {

            }
        }

    }
}